package com.AJava1710D.bingfabao.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 作者: LCG
 * 日期: 2020/6/24 09:29
 * 描述:
 */
public class TestCompletableFuture000 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //让两个线程一前一后的运行并且后者依赖前者的运行结果
        /*CompletableFuture.supplyAsync(()->{
            System.out.println("执行的任务1");
            return "OK1";
        }).thenAccept(x->{
            System.out.println("执行的任务1");
            System.out.println(x+"-->OK2");
        });*/

        //多个任务的结果合并
       /* CompletableFuture.supplyAsync(()->{
            System.out.println("=========1");
            return "OK1";
        }).thenCombineAsync(CompletableFuture.supplyAsync(()->{
            System.out.println("=========2");
             return "--OK2--";
        }),(x1,x2)->{
             return x1+x2;
        }).thenCombineAsync(CompletableFuture.supplyAsync(()->{
            System.out.println("=========3");
            return "OK3";
        }),(x2,x3)->{
            return x2+x3;
        }).thenAccept(x->{
            System.out.println(x);
        });*/


        //返回运行最快的一个线程的结果
        CompletableFuture<String> stringCompletableFuture1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "OK1";
        });
        CompletableFuture<String> stringCompletableFuture2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "OK2";
        });


        CompletableFuture<String> stringCompletableFuture3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "OK3";
        });


        /*CompletableFuture<Object> objectCompletableFuture = CompletableFuture.anyOf(stringCompletableFuture1, stringCompletableFuture2, stringCompletableFuture3);

        System.out.println(objectCompletableFuture.get());

        System.out.println("==========0000000========");*/


        //当所有的任务全部完成的场景的使用
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(stringCompletableFuture1, stringCompletableFuture2, stringCompletableFuture3);
        voidCompletableFuture.get();

        System.out.println("===="+stringCompletableFuture1.get()+"==="+stringCompletableFuture2.get()+"==="+stringCompletableFuture3.get());


    }

}
